<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { querySelectTreeTableApi } from '#/api';
import {
  designPageAddApi,
  designPageEditApi,
  designPageQueryByIdApi,
} from '#/api/gen/designPage';
import { genModelClassifyQueryClassifyAndModelApi } from '#/api/gen/modelType';
import { roleQueryListApi } from '#/api/system/role';
import { queryDictOptionsApi } from '#/utils';

const record = ref({});
const classifyModels = ref([]);

const [PageForm, formApi] = useVbenForm({
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'ApiRadioGroup',
      formItemClass: 'col-span-2',
      defaultValue: 'table',
      componentProps: {
        disabled: true,
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: item.itemVal,
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'online_page_type',
        },
      },
      fieldName: 'pageType',
      label: '页面类型',
      rules: 'required',
    },
    {
      component: 'ApiRadioGroup',
      formItemClass: 'col-span-2',
      defaultValue: 'table',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: item.itemVal,
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'online_page_layout',
        },
      },
      fieldName: 'layout',
      label: '布局',
      rules: 'required',
      dependencies: {
        triggerFields: ['id'],
        disabled(values) {
          return !!values.id;
        },
      },
    },
    {
      component: 'Select',
      fieldName: 'mainModel',
      label: '主模型',
      rules: 'required',
      formItemClass: 'col-span-2',
      componentProps: {
        placeholder: '请选择主模型',
      },
      dependencies: {
        triggerFields: ['id'],
        disabled(values) {
          return !!values.id;
        },
      },
    },
    {
      component: 'ApiRadioGroup',
      label: '生成菜单',
      formItemClass: 'col-span-2',
      defaultValue: 0,
      fieldName: 'genSql',
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'yes_or_no',
        },
      },
    },
    {
      component: 'Input',
      label: '菜单名称',
      fieldName: 'menuName',
      rules: 'required',
      componentProps: {
        placeholder: '请输入菜单名称',
      },
      dependencies: {
        triggerFields: ['genSql'],
        show(values) {
          return values.genSql === 0;
        },
      },
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        api: () =>
          querySelectTreeTableApi({
            tableName: 'sys_permission',
            labelField: 'name',
            valueField: 'pid',
            sortRankField: 'sort_rank',
            sqlSelect: 'del_flag = 0',
          }),
        placeholder: '请选择上级菜单',
        labelField: 'name',
        childrenField: 'children',
        valueField: 'id',
      },
      fieldName: 'parentMenuId',
      label: '上级菜单',
      dependencies: {
        triggerFields: ['genSql'],
        show(values) {
          return values.genSql === 0;
        },
      },
    },
    {
      component: 'ApiRadioGroup',
      label: '授权',
      defaultValue: 0,
      fieldName: 'isAuth',
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'yes_or_no',
        },
      },
    },
    {
      component: 'ApiSelect',
      componentProps: {
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.roleName,
            value: item.id,
          }));
        },
        // 菜单接口
        api: roleQueryListApi,
        allowClear: true,
      },
      fieldName: 'auths',
      label: '目标角色',
      rules: 'required',
      dependencies: {
        triggerFields: ['isAuth'],
        show(values) {
          return values.isAuth === 0;
        },
      },
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  title: '页面',
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = modalApi.getData<Record<string, any>>();
      modalApi.setState({
        title: `${record.value.id ? '编辑' : '新增'}页面`,
      });
      loadModelClassify();
      if (record.value.id) {
        initFun();
      }
    }
  },
});

const classifyModelsOptions = computed(() => {
  return classifyModels.value.map((item) => ({
    label: item?.name || '未命名分类',
    options: (item.models || []).map((child) => ({
      value: child.modelCode,
      label: child.modelName,
    })),
  }));
});

async function loadModelClassify() {
  classifyModels.value = await genModelClassifyQueryClassifyAndModelApi();
}

async function initFun() {
  const res = await designPageQueryByIdApi({ id: record.value.id });
  res.auths = res.auths ? res.auths.split(',') : [];
  await formApi.setValues(res, false);
}

async function onSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    const updatedValues = { ...values };
    if (record.value.id) {
      const msg = await designPageEditApi(updatedValues);
      message.success(msg);
      await modalApi.close();
    } else {
      const msg = await designPageAddApi(updatedValues);
      message.success(msg);
      await modalApi.close();
    }
  }
}
</script>

<template>
  <Modal>
    <PageForm>
      <template #mainModel="slotProps">
        <a-select v-bind="slotProps" :options="classifyModelsOptions" />
      </template>
    </PageForm>
  </Modal>
</template>
